package com.ebelter.seneo.ui.activitys;


import android.content.Intent;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserinfos;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.R;
import com.ebelter.seneo.adapters.HostoryListAdapter;
import com.ebelter.seneo.beans.HostoryListData;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.models.SeneoDbUtils;
import com.ebelter.seneo.models.SeneoNet;
import com.ebelter.seneo.ui.fragments.main.Trend_Fragment;
import com.ebelter.seneo.ui.views.LineView;
import com.ebelter.seneo.utils.SeneoUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class SeneoHistoryListActivity extends SeneoBaseActivity {
    public static final String TAG = "HistoryListActivity";

    public static final String Userid = "Userid";

    ImageView top_iv;
    TextView top_tv1;
    RelativeLayout no_history_ly;
    ListView history_lv;
    private HostoryListAdapter adapter;

    private int startPage;
    private int pageSize=30;
    private long lastLoadingTime;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_seneo_history_list;
    }


    View listFootView;
    TextView noMoreTv;

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        FV();
        history_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.i(TAG,"----获取到的数据是---"+adapter.getData().get(position));

                Intent deatilIntent=new Intent(SeneoHistoryListActivity.this,SeneoHistoryItemDetailActivity.class);
                deatilIntent.putExtra(SeneoHistoryItemDetailActivity.ITEMDATD,adapter.getData().get(position));
                startActivityForResult(deatilIntent,10);
            }
        });

    }

    private long userid;
    @Override
    protected void initData() {
        adapter = new HostoryListAdapter(this);
        history_lv.setAdapter(adapter);

        listFootView = View.inflate(this, R.layout.no_history, null);
        noMoreTv=listFootView.findViewById(R.id.no_data_tv);
        noMoreTv.setText(R.string.No_more);
        noMoreTv.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        history_lv.addFooterView(listFootView);
        ViewUtils.hideView(listFootView);

        userid = getIntent().getLongExtra(Userid,0);

        if (NetUtils.available()){
            getHostoryListDatas(startPage,pageSize);
        }else {
            ToastUtil.show(R.string.Network_error);
            if (adapter!=null){
                if (adapter.getCount()==0){
                    ViewUtils.displayView(no_history_ly);
                }else {
                    ViewUtils.hideView(no_history_ly);
                }
            }
        }



        history_lv.setOnScrollListener(new AbsListView.OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState){
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        //加载更多功能的代码
                        if (System.currentTimeMillis()-lastLoadingTime>3000){
                            LogUtils.i(TAG,"---------加载更多");
                            lastLoadingTime = System.currentTimeMillis();
                            getHostoryListDatas(++startPage,pageSize);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
    }

    public void getHostoryListDatas(int startPage,int pageSize) {
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("userId", userid);
        paramMap.put("startIndex", startPage);
        paramMap.put("pageSize", pageSize);
        LogUtils.i(TAG,"----userId="+userid+"----startIndex="+startPage+"---pageSize="+pageSize);

        SeneoNet.getIntance().getsHostoryListData(this, paramMap, new HttpResponse<HostoryListData>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, HostoryListData hostoryListData,String s) {
                if (isRequestSuccess){
                    LogUtils.i(TAG,hostoryListData.toString());
                    if (hostoryListData.resultCode==0){
                        //2018-06-19 12:15:12
                        if (adapter!=null){
                            if (hostoryListData.getResultData()!=null&&hostoryListData.getResultData().getData()!=null){
                                adapter.addData(hostoryListData.getResultData().getData());
                                if (hostoryListData.getResultData().getData().size()==0){
                                    ViewUtils.displayView(listFootView);
                                }
                            }
                        }
                    }
                }else {
                    ToastUtil.show(R.string.Network_connection_error);
                }

                if (adapter!=null){
                    if (adapter.getCount()==0){
                        ViewUtils.displayView(no_history_ly);
                    }else {
                        ViewUtils.hideView(no_history_ly);
                    }
                }


            }
        });
    }

    private void FV() {
        top_iv=findViewById(R.id.top_iv);
        top_tv1=findViewById(R.id.top_tv1);

        top_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        top_tv1.setText(R.string.history);
        ViewUtils.displayView(top_tv1);
        no_history_ly=findViewById(R.id.no_history_ly);
        history_lv = findViewById(R.id.history_lv);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommonEventBus event) {
        if (!event.whichReceive.contains(TAG)) {
            return;
        }
        LogUtils.i(TAG, TAG+"--onEventMainThread接收到CommonEventBus信息--" + event.toString());
        if (event.cmd== IUserContant.ICMDS.DELETE_DATA_SUCCESS){
            LogUtils.i(TAG, TAG+"--onEventMainThread接收到删除数据成功");
            Object[] objects = (Object[]) event.getContent();
            //objects[0]=id;
            //objects[1]=userid;
            if (adapter!=null){

//                objects[0]=id;
//                objects[1]=userid;

                int positionIndex = adapter.deleteById((String) objects[0]);



                if (adapter.getCount() == 0){
                    ViewUtils.displayView(no_history_ly);
                }else {
                    ViewUtils.hideView(no_history_ly);
                }

                SeneoUtils.sendCommonEventBus(TAG, Trend_Fragment.TAG, IUserContant.ICMDS.REQUEST_TREND_DATA,"删除数据成功，重新请求趋势数据");

                if (positionIndex==0){
                    //拿到最新的测量数据
                    HostoryListData.ResultDataBean.DataBean newdata = adapter.getItemData(0);
                    CommonEventBus commonEventBus=new CommonEventBus(TAG,SeneoMainActivity.TAG, IUserContant.ICMDS.UPDATA_CURRENT_USER_MEASURE_DATA,"更新当前用户的测量信息");
                    commonEventBus.setContent(newdata);
                    EventBus.getDefault().post(commonEventBus);
                }

            }

        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
}
